<template>
  <div class="common">
    <el-text style="font-size: 16px">模板信息</el-text>
    <div class="action">
      <el-button type="primary" @click="back">返回</el-button>
      <el-button type="primary" @click="saveFormJson">保存</el-button>
    </div>
    <div class="line"></div>
    <div class="info">
      <div style="display: flex">
        <el-form-item label="模板名称：" style="margin-right: 30px" required>
          <!-- <el-select class="selectStyle" @change="showForm" placeholder="请选择安全档案模板">
            <el-option>外部单位模板一</el-option>
          </el-select> -->
            <el-input v-model="modelName" placeholder="请输入模板名称"  clearable :disabled="disabled"/>
        </el-form-item>
        <el-form-item label="单位类型" required>
          <el-select class="selectStyle" placeholder="请输入单位类型" v-model="unitType" :disabled="disabled">
            <el-option
              v-for="item in unitTypeList"
              :key="item.id"
              :label="item.catalogueName"
              :value="item.id"
            />
          </el-select>
        </el-form-item>
      </div>
    </div>
    <div style="border-top: 1px solid var(--el-border-color);"></div>
    <v-form-designer resetFormJson="true" ref="vfDesigner" :field-list-api="fieldListApi" :banned-widgets="testBanned"
                   :designer-config="designerConfig">
    </v-form-designer>
  </div>

  <getFormJson @getFormJson="getFormJson" :jsonData="jsonData"></getFormJson>
</template>

<script lang="ts" setup>
  import { computed, ref, reactive, onBeforeMount, nextTick, onMounted,defineExpose } from "vue";
  import LayoutCard from "@/components/LayoutCard/index.vue";
  import { newModelOptions } from "@/views/secure/archives/model/config/filters";
  import { useStore } from 'vuex';
  import {
    ElMessage,

  } from "element-plus";
  import {saveModel, getModelData,updateJson} from '@/api/secure/securityTemplateManager'
  import {listIdAndType} from '@/api/secure/catalogue'
import { number } from "echarts";


  // 获取登录用户信息
	const { getters } = useStore();
	// 用户信息
	const UserInfo = computed(() => getters['user/getUserInfo']);

  //模板名称
  const modelName = ref(null)
  const unitType = ref(null)
  const jsonData = ref()

  const disabled = ref(false)

  const unitTypeList = ref([])

  const props = defineProps<{
    model: number
  }>()

  onMounted(() => {
    if(props.model != undefined || props.model != null) {
      getFormJsonData(props.model)
    }
    listIdAndType().then(res => {
      if(res.code === '1' && res.data) {
        unitTypeList.value = res.data;
      }
    })
  })

  // const unitTypeList = computed(() => {
  //   //单位类型 todo
  //   listIdAndType().then(res => {
  //     if(res.code === '1' && res.data) {
  //       return res.data;
  //     }
  //   })
  // });



  const emit = defineEmits(["getValue2"]);
  const vfDesigner = ref(null)
  const fieldListApi = reactive({
    URL: 'https://www.fastmock.site/mock/2de212e0dc4b8e0885fea44ab9f2e1d0/vform/listField',
    labelKey: 'fieldLabel',
    nameKey: 'fieldName'
  })
  const testBanned = ref([
    //'sub-form',
    //'alert',
  ])
  const designerConfig = reactive({
    languageMenu: true,
    //externalLink: false,
    //formTemplates: false,
    //eventCollapse: false,
    //clearDesignerButton: false,
    //previewFormButton: false,

    //presetCssCode: '.abc { font-size: 16px; }',
  })

  const saveFormJson = () => {
    //如果是编辑页面 则点击保存走更新接口
    if(props.model != undefined || props.model != null) {
      updateJsonData()
      return
    }
    let formJson = vfDesigner.value.getFormJson()
    const listParam = {
      modelName: modelName.value,
      formJson: JSON.stringify(formJson),
      createUserName: UserInfo.value.userName,
      createUserId: Number(UserInfo.value.userId),
      catalogueId: unitType.value
    }
    console.log(listParam)
    saveModel(listParam).then(res => {
      if(res.code === '1') {
        ElMessage.success(res.message)
        //返回上一页
        back()
      }else {
        ElMessage.error(res.message)
      }
    })
  }

  const updateJsonData = () => {
    let formJson = vfDesigner.value.getFormJson()
    const paramsUpdate = {
      formJson: JSON.stringify(formJson),
      modelName: modelName.value,
      catalogueId: unitType.value,
      modelId: props.model
    }
    updateJson(paramsUpdate).then(res => {
      if(res.code === '1') {
        ElMessage.success(res.message)
        //返回上一页
        back()
      }else {
        ElMessage.error(res.message)
      }
    })
  }

  const getFormJsonData = (val:any) => {

    getModelData(val).then(res => {
      if(res.code === '1') {
        ElMessage.success(res.message)
        vfDesigner.value.setFormJson(res.data.formJson);
        modelName.value = res.data.modelName
        unitType.value = res.data.catalogueIdStr
      }else {
        ElMessage.error(res.message)
      }
    })
  }

  /**
   * 返回，回到index
   */
  const back = () => {
    //清空设计器画布
    vfDesigner.value.clearDesigner()
    props.model = null
    emit("getValue2",false)
  };

  /**
   * @functionName 获取数据
   * @author 彭庆楠
   * @date 2023-08-08 17:47:31
   * @version V1.0.0
   * @return
   */
  const getData = async () => {

  };

  // 删除
  const DeletRow = (row: any) => {
    const formData = new FormData();
    formData.append("houseId", row.houseId);
  };

  const showForm = () => {

  }
  /**
   * @functionName 重置功能
   * @param {FilterDataType} data
   * @description
   * @author 杜思成
   * @date 2023-08-17 17:55:57
   * @version V1.0.0
   * @return
   */
  const searchReset = (data: FilterDataType) => {
    getData();
  };

  defineExpose({
    getFormJsonData
  })
</script>
<style scoped>


.common{
  padding: 10px 10px;
  height: 100%;
}
:deep(.main-header) {
  display: none;
}
.action{
  float: right;
  margin-top: -20px;
  position: relative;
}
.line{
  border-top: 1px solid #1caad5;
  /*margin-top: 40px;*/
  margin-bottom: 20px;
}
.selectStyle{
  width: 300px;
}
</style>
